import * as joi from "joi";
import {
  Controller,
  Get,
  QuerySchame,
  Query,
  Ctx,
  Post,
  BodySchame,
  Body,
  Description,
} from "@/common/application";
import { ResultUtils } from "@/utils/result-utils";
import xhsUserModel from "@/model/xhsUser.model";
import Role from "@/decorators/role";
import { xhsUserManager } from "@/service/xhsUserManager";
import { WebSocketManager } from "@/service/WebSocketManager";
import * as moment from "moment";
import { log } from "console";
import getLogger from "@/utils/log4js";
import async from "async";
import { spawn, ChildProcess } from "child_process"; // 导入 child_process 模块

const logger = getLogger("LogcatManager");

// 创建一个队列，限制并发数为 1
const queue = async.queue(async (task, done) => {
  try {
    // 从任务中获取状态为 0 的用户列表
    const xhsUsers = await xhsUserModel.getXhsUserAppList({
      status: 0,
      message_status: 0,
    });

    if (xhsUsers.length > 0) {
      // 批量更新用户状态
      const updatePromises = xhsUsers.map((user) => {
        user.status = 1;
        return xhsUserModel.updateUserStatus(user.xhs_user_id, 1);
      });
      await Promise.all(updatePromises);
      // 假设有一个方法用于更新用户状态
      logger.info(`Updated ${xhsUsers.length} xhsUser statuses to 1`);
    }
    // 任务完成，返回 xhsUsers 作为结果
    done(null, xhsUsers);
  } catch (error) {
    logger.error("Failed to get xhsUser app list or update statuses", error);
    done(error); // 任务失败
  }
}, 1); // 设置并发数为 1

let isCrawlerRunning = false; // 定义一个状态变量
let crawlerProcess: ChildProcess | null = null;

@Controller("/xhsUser")
@Description("小红书用户")
export class xhsUser {
  // @Get('/get_device_list')
  // @Description('获取设备列表')
  // async get_device_list() {
  //   const devices = await xhsUserModel.getAll();
  //   return ResultUtils.success({ devices });
  // }
  @Post("/run_crawler")
  @Description("运行爬虫脚本")
  async run_crawler(@Body()
  body: {
    platform: string;
    loginType: string;
    crawlerType: string;
    cookies: string;
    crawlerSortType: string;
    startPage: string;
    crawlerMaxNotesCount: string;
    keywords: string;
    filterKeywords: string;
    xhsSpecifiedIds: string;
  }) {
    if (isCrawlerRunning) {
      return ResultUtils.internalServerError("爬虫脚本正在运行，请稍后再试");
    }

    isCrawlerRunning = true;

    return new Promise((resolve, reject) => {
      // 这里传递了 --platform, --lt 和 --type 参数
      crawlerProcess = spawn("python3", [
        "/Users/gohi/Desktop/MediaCrawler/main.py",
        "--platform",
        body.platform, // 传递 platform 参数
        "--lt",
        body.loginType, // 传递 lt 参数
        "--type",
        body.crawlerType, // 传递 type 参数
        "--start",
        body.startPage, // 传递 爬取开始页数 参数
        "--crawler_max_notes_count",
        body.crawlerMaxNotesCount, // 传递 爬取最大 参数
        "--keywords",
        body.keywords, // 传递 爬取关键词 参数
        "--filter_keywords",
        body.filterKeywords, // 传递 过滤词 参数
        "--xhs_ids",
        body.xhsSpecifiedIds, // 传递 帖子数组 参数
        "--cookies",
        body.cookies, // 传递 cookies 参数
      ]);

      let output = "";
      let errorOutput = "";
      const wsManager = WebSocketManager.getInstance();
      crawlerProcess.stdout.on("data", (data) => {
        output += data.toString();
        logger.error("Crawler stdout", output);
        // 通过 WebSocket 发送实时输出到客户端
        wsManager.broadcast({ type: "crawler_output", data: data.toString() });
      });

      crawlerProcess.stderr.on("data", (data) => {
        errorOutput += data.toString();
        logger.error("Crawler script failed with code", errorOutput);
        wsManager.broadcast({ type: "crawler_output", data: data.toString() });
      });

      crawlerProcess.on("close", (code) => {
        isCrawlerRunning = false; // 重置状态变量
        crawlerProcess = null;
        if (code !== 0) {
          logger.error("Crawler script failed with code", code, errorOutput);
          return resolve(ResultUtils.internalServerError("运行爬虫脚本失败"));
        }

        logger.info("Crawler script output:", output);
        wsManager.broadcast({ type: "crawler_output", data: output });
      });

      crawlerProcess.on("error", (error) => {
        isCrawlerRunning = false; // 重置状态变量
        crawlerProcess = null;
        logger.error("Failed to start crawler script:", error);
        wsManager.broadcast({ type: "crawler_output", data: error });
        return reject(ResultUtils.internalServerError("启动爬虫脚本失败"));
      });
      return resolve(ResultUtils.success());
    });
  }

  @Post("/stop_crawler")
  @Description("停止爬虫脚本")
  async stop_crawler() {
    if (!isCrawlerRunning || !crawlerProcess) {
      return ResultUtils.internalServerError("没有正在运行的爬虫脚本");
    }

    try {
      crawlerProcess.kill();
      isCrawlerRunning = false;
      crawlerProcess = null;
      return ResultUtils.success("爬虫脚本已停止");
    } catch (error) {
      logger.error("Failed to stop crawler script:", error);
      return ResultUtils.internalServerError("停止爬虫脚本失败");
    }
  }

  @Get("/get_xhsUser_list")
  @Description("获取小红书用户列表")
  async get_xhsUser_list() {
    const xhsUser = await xhsUserModel.getAll();
    return ResultUtils.success({ xhsUser });
  }

  @Get("/get_xhsUser_appList")
  @Description("获取小红书用户app执行列表")
  async get_xhsUser_appList() {
    try {
      // 返回一个 Promise，以便在队列任务完成时可以用 await 等待结果
      const xhsUsers = await new Promise((resolve, reject) => {
        queue.push({}, (err, users) => {
          if (err) {
            console.error("Queue task failed:", err);
            reject(err); // 任务失败时拒绝 Promise
          } else {
            console.log("Queue task completed successfully. xhsUsers:", users);
            resolve(users); // 任务成功时解析 Promise
          }
        });
      });

      // 返回获取到的 xhsUsers 数据
      return ResultUtils.success({ xhsUsers });
    } catch (error) {
      // 捕捉错误并记录日志
      logger.error("Failed to get xhsUser app list", error);
      return ResultUtils.internalServerError("获取小红书用户app执行列表失败");
    }
  }

  @Post("/add_xhsUser")
  @Description("新增小红书用户")
  async add_device(@Body() body: any) {
    await xhsUserModel.insert(body);
    return ResultUtils.success();
  }

  @Post("/update_xhsUser")
  @Description("编辑小红书用户")
  async update_device(@Body() body: any) {
    const xhsUser = await xhsUserModel.getById(body.xhs_user_id);
    if (xhsUser.status == 1) {
      xhsUser.status = 0;
      xhsUser.message_status = 1;
    }
    xhsUser.message_time = moment(xhsUser.message_time || new Date()).format(
      "YYYY-MM-DD HH:mm:ss"
    );
    await xhsUserModel.updateById(body.xhs_user_id, xhsUser);
    return ResultUtils.success();
  }

  @Post("/remove_xhsUser")
  @Description("删除小红书用户")
  async remove_device(@Body() body: any) {
    await xhsUserModel.deleteById(body.xhs_user_id);
    return ResultUtils.success();
  }
}
